<?php
/**
 * This file is part of the Agora distribution. 
 * Detailed copyright and licensing information can be found
 * in the gpl-3.0.txt file which should be included in the distribution.
 * 
 * @version		$Id: 3.0.14 Olympus 2010-09-28 rammstein4o $
 * @copyright  2007 - 2010 jVitals
 * @license   GPLv3 Open Source
 * @link       http://jvitals.com
 * @since      File available since initial release
 */	
defined ('IN_AGORA') or die;

class TaskController extends AgoraCommonController {
	function TaskController() {
		$this->__construct();
	}

	function _execute()	{
	}
	
	function __construct() {
		$this->db = & JFactory::getDBO();
        $lang = & JFactory::getLanguage();
        $lang->load('com_agora',JPATH_ROOT);
	}

	function checkPath($path) {
		
		$parts = explode(DS, $path);
		$temp_path = JPATH_ROOT;
		
		if ($path[0] !== '/') {
			$path = JPath::clean(JPATH_ROOT.DS.$path);
		}
		
		if (is_array($parts) && count($parts) > 0) {
			foreach ($parts as $part) {
				$temp_path .= DS . $part;
				if (!file_exists($temp_path)) {
					echo '<span style="color: #FF0000">'.Agora::lang('DIR_NOT_FOUND').' - ' . $temp_path . '</span>';
					@mkdir($temp_path);
					if (!file_exists($temp_path)) {
						echo '<span style="color: #FF0000">'.Agora::lang('DIR_CREATE_FAILED').' - ' . $temp_path . '</span>';
					}

				}
			}
		}

		$r = false;

		if (is_dir($path) && is_writable($path)) {
			echo '<span style="color: #00FF00">Ok</span>';
			$r = true;
		} elseif (file_exists($path) && !is_dir($path)) {
			echo '<span style="color: #FF0000">'.Agora::lang('DIR_NOT_DIR').'</span>';
		} elseif (file_exists($path)) {
			echo '<span style="color: #0000FF">'.Agora::lang('DIR_NOT_WRITABLE').'</span>';
			if (is_writable($path)) {
				echo '<span style="color: #00FF00">Ok</span>';
				$r = true;
			} else {
				echo '<span style="color: #F00F00">'.Agora::lang('DIR_CHMOD_FAILED').'</span>';
			}
		}
		echo "<br/>\n";

		if (!$r) {
			echo '<strong>';
			$link = '<a href="javascript:void(0);" onClick="agora_checkDirs()">'.Agora::lang('CHECK_DIR_PERMISSIONS').'</a>';
			echo Agora::lang('DIR_PERMISSIONS_FAILED',$link);
			echo '</strong><br/><br/>'."\n";
		}
		return $r;
	}

	function checkDirs() {
		// $uri = & JFactory::getURI();
		// $uri = $uri->toString();
		
		echo '<h2>'.Agora::lang('Directory_permissions').'</h2>';

		$this->db->setQuery('SELECT conf_value FROM #__agora_config WHERE conf_name=\'o_avatars_dir\'');
		$path = $this->db->loadResult();
		echo Agora::lang('CHECK_AVATARS',$path).' ';
		$this->checkPath($path);

		$path = 'cache' . DS . 'com_agora';
		echo Agora::lang('CHECK_CACHE',$path).' ';
		$this->checkPath($path);

		$path = 'components' . DS . 'com_agora'. DS. 'img'. DS. 'members';
		echo Agora::lang('CHECK_UPLOADS',$path).' ';
		$this->checkPath($path);

		$path = 'components' . DS . 'com_agora'. DS. 'img'. DS. 'members'.DS.'*';
		$dirs = glob(JPATH_ROOT.DS.$path,GLOB_NOSORT | GLOB_ONLYDIR | GLOB_NOESCAPE);
		if (!$dirs) return;
		foreach ($dirs as $dir) {
			$dir = str_replace(JPATH_ROOT.DS, '', $dir);
			echo Agora::lang('CHECK_EXISTING_UPLOADS',$dir).' ';
			$this->checkPath($dir);
		}
	}

	function installClean() {
		echo '<h2>'.Agora::lang('CLEAN_DATABASE').'</h2>';

		$this->db->setQuery('SHOW TABLES LIKE \'%\_agora\_%\'');
		$tables = $this->db->loadResultArray();
		echo Agora::lang('FOUND_OLD_TABLES',count($tables))."<br/>\n";

		$dropped = 0;
		foreach ($tables as $table) {
			$this->db->setQuery('DROP TABLE '.$table);
			if ($this->db->query()) {
				$dropped += 1;
			}
		}
		echo Agora::lang('DROPPED_OLD_TABLES',$dropped)."<br/>\n";

		echo Agora::lang('RUNNING_SQL_FILES')."<br/>\n";
		require_once(JPATH_COMPONENT_ADMINISTRATOR.DS.'install.agora.php');
		$installer = new AgoraInstaller();

		$cnt = $installer->runSQLFile('install.agora.sql');
		echo 'install.agora.sql: '.$cnt.' '.Agora::lang('QUERIES_PROCESSED')."<br/>\n";

		$cnt = $installer->runSQLFile('upgrade.fresh.sql');
		echo 'upgrade.fresh.sql: '.$cnt.' '.Agora::lang('QUERIES_PROCESSED')."<br/>\n";

		foreach ($installer->logList as $logs) {
			switch ($logs->type) {
				case 'error': $color = '#FF0000'; break;
				case 'info': $color = '#0000FF'; break;
				default: $color = '#000000';
			}
			echo '<span color="'.$color.'">'.$logs->message.'</span><br/>'."\n";
		}
	}

	function syncUsers()
	{
		echo '<h2>'.Agora::lang('SYNC_USERS').'</h2>';
		// remove delete users from Agora tables
		$users_model = & Model::getInstance('UserModel');

		$this->db->setQuery('SELECT ag.id'.
						' FROM #__agora_users AS ag'.
						' LEFT JOIN #__users AS jos'.
						'  ON jos.id=ag.jos_id'.
						' WHERE jos.id IS NULL');
		$deleted = $this->db->loadResultArray();
		$users_model->deleteList($deleted);

		echo Agora::lang('DELETED_USERS',$deleted)."<br/>\n";
		
		// add new users to Agora
		$this->db->setQuery('SELECT jos.id, jos.lastvisitDate, jos.registerDate, jos.username, jos.email, jos.usertype'.
						' FROM #__agora_users AS ag'.
						' RIGHT JOIN #__users AS jos'.
						'  ON jos.id=ag.jos_id'.
						' WHERE ag.jos_id IS NULL');

		$new = $this->db->loadObjectList();

		foreach ($new as $user) {
			$users_model->createUserFromJoomla($user);
		}
		echo Agora::lang('ADDED_USERS',count($new))."<br/>\n";
	}
	
	function recountPosts()
	{
		echo '<h2>'.Agora::lang('RECOUNT_POSTS').'</h2>';
		// remove delete users from Agora tables
		$users_model = & Model::getInstance('UserModel');
		
		/*
		$this->db->setQuery('UPDATE #__agora_topics SET num_replies = 
							(select count(*)-1 from #__agora_posts 
							WHERE topic_id=#__agora_topics.id)');
		*/
		$this->db->setQuery(
			'UPDATE #__agora_topics t 
				JOIN (SELECT topic_id, (COUNT(id) - 1) as posts FROM #__agora_posts WHERE approved = 1 GROUP BY topic_id) as p 
					ON t.id = p.topic_id 
			SET t.num_replies = p.posts');
		$this->db->query();
		echo Agora::lang('RECOUNT_POSTS_END')."<br/>\n";
		
		/*
		$this->db->setQuery('UPDATE #__agora_forums SET
							num_topics = (select count(*) from #__agora_topics 
							WHERE forum_id=#__agora_forums.id), num_posts = COALESCE((select sum(num_replies) 
							FROM #__agora_topics WHERE forum_id = #__agora_forums.id),0)');
		*/
		$this->db->setQuery(
			'UPDATE #__agora_forums f 
				JOIN (SELECT forum_id, SUM(num_replies) as posts, COUNT(id) as topics FROM #__agora_topics WHERE approved = 1 GROUP BY forum_id) as t 
					ON f.id = t.forum_id 
			SET f.num_posts = t.posts, 
				f.num_topics = t.topics');
		$this->db->query();
		
	}
	
	
	function addallUsersToGlobal() {
	
		echo '<h2>'.Agora::lang('ALL_USERS_TO_GLOBAL_GROUP').'</h2>';
		
		$group_model =& Model::getInstance('GroupModel');
		
		$this->db->setQuery('SELECT id FROM #__agora_users');		
		$list = $this->db->loadResultArray();
		
		foreach ($list as $user_id) {
			$group_model->addUser(1, $user_id, 2);
		}
		
		echo Agora::lang('ALL_USERS_TO_GLOBAL_GROUP_END')."<br/>\n";
		
	}
	
	function recountUserPosts() {
		echo '<h2>'.Agora::lang('RECOUNT_USER_POSTS').'</h2>';
		// remove delete users from Agora tables
		$users_model = & Model::getInstance('UserModel');		
		
		/*
		$this->db->setQuery('UPDATE #__agora_users SET num_posts = 
							(select count(*) from #__agora_posts 
							WHERE poster_id=#__agora_users.id)');
		*/
		
		$this->db->setQuery(
			'UPDATE #__agora_users u 
				JOIN (SELECT poster_id, COUNT(id) as posts FROM #__agora_posts WHERE approved = 1 GROUP BY poster_id) as p 
					ON u.id = p.poster_id 
			SET u.num_posts = p.posts');

		$this->db->query();
		
		echo Agora::lang('RECOUNT_USER_POSTS_END')."<br/>\n";
		
	}
	
	
	protected function dirlist($dir) {
		$listarray = array();
		foreach(scandir($dir) as $entry) {
			if($entry != '.' && $entry != '..') {
				$entry  = $dir.'/'.$entry;
				if(is_dir($entry)) {
					$path = pathinfo($entry);
					$listarray[$path['basename']] = $this->dirlist($entry);
				} else {
					$path = pathinfo($entry);
					$listarray[] = $path['basename'];
				}
			}
		}
		return($listarray);
	}

	
	
	function generateHtmlArticles() {
		echo '<h2>'.Agora::lang('GENERATE_HTML_ARTICLES').'</h2>';
		$query = 'SELECT a.*, u.name AS author, u.usertype, cc.title AS category, s.title AS section,' .
				' CASE WHEN CHAR_LENGTH(a.alias) THEN CONCAT_WS(":", a.id, a.alias) ELSE a.id END as slug,'.
				' CASE WHEN CHAR_LENGTH(cc.alias) THEN CONCAT_WS(":", cc.id, cc.alias) ELSE cc.id END as catslug,'.
				' g.name AS groups, s.published AS sec_pub, cc.published AS cat_pub, s.access AS sec_access, cc.access AS cat_access '.$voting['select'].
				' FROM #__content AS a' .
				' LEFT JOIN #__categories AS cc ON cc.id = a.catid' .
				' LEFT JOIN #__sections AS s ON s.id = cc.section AND s.scope = "content"' .
				' LEFT JOIN #__users AS u ON u.id = a.created_by' .
				' LEFT JOIN #__groups AS g ON a.access = g.id'.
				' ORDER BY a.created ASC'.
				' LIMIT 1000';
		$this->db->setQuery($query);
		$articles = $this->db->loadAssocList();
		
		$articles_path = JPATH_ROOT.DS.'media'.DS.'articles2_html';
		$i=0;
		
		/*
		$j=0;
		$num__ = $this->dirlist($articles_path); 
		foreach ($num__ as $num_)
			foreach ($num_ as $num)
			$j += count($num);
			echo $j;
		exit;
		*/
		
		foreach (array(JPATH_ROOT.DS.'media',$articles_path) as $apath) {
			if (!is_dir($apath)) {
				if(!mkdir($apath)) {
					echo "Error. Illegal rights to make $apath folder<br/>\n";
					return;
				} else {
					echo "Success. Made $apath folder<br/>\n";
				}
			}
		}
		
		foreach ($articles as $article) {
			$section = str_replace(' ', '_', $article["section"]);
			$category = str_replace(' ', '_', $article["category"]);
			$cur_article_path = $articles_path."/$category";
			
			if (!is_dir($cur_article_path)) {
				if (!mkdir($cur_article_path)) {
					echo "Error. Illegal rights to make $cur_article_path folder<br/>\n";
					break 1;
				} else {
					echo "Success. Made $cur_article_path folder<br/>\n";
				}
			}
				
			if ($article["alias"]) {
				$filetitle = $article["alias"];
			} else {
				$filetitle = preg_replace("/[^A-Za-z0-9]/", '-', $article["title"]);
			}
			
			$fname = $cur_article_path.DS.$filetitle.'.html';
			if (($fh = fopen($fname, "w+b")) === FALSE) {
				echo "Error. Illegal rights to make $fname file<br/>\n";
				break 1;
			}
				
			$title=$article["title"];
			$introtext=$article["introtext"].'<br/>';
			$fulltext=$article["fulltext"].'<br/>';
			$author='Author: '.$article["author"].'<br/>';
			$created='Created: '.$article["created"].'<br/>';

			$file_content=array();
			$file_content[]='<html xmlns="http://www.w3.org/1999/xhtml">';
			$file_content[]='<head>';
			$file_content[]='<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />';
			$file_content[]="<title>$title</title>";
			$file_content[]='</head>';
			$file_content[]='<body>';

			$file_content[]=$author;
			$file_content[]=$created;
			$file_content[]=$introtext;
			$file_content[]=$fulltext;

			$file_content[]='</body>';
			$file_content[]='</html>';

			$status=1;
			foreach ($file_content as $content) {
				if ( 'FALSE' === fwrite($fh, $content) )
				$status=0;
			}

			fclose($fh);
			if (!$status) {
				echo "Error. Couldn't wright data to $fname<br/>\n";
				break 1;
			} else {
				echo "Success. Data was written to $fname<br/>\n";
			}

			$this->db->setQuery('DELETE FROM #__content WHERE id='.$article["id"]);
			if (!$this->db->query()) {
				echo "Error. Couldn't delete id=".$article["id"]." from article db table<br/>\n";
				break 1;
			} else {
				echo "Success. Article db record was deleted<br/>\n";
			}
		}
		echo Agora::lang('GENERATE_HTML_ARTICLES_END')."<br/>\n";
		
	}
	
	function fixUserDuplication()
	{
		echo '<h2>'.Agora::lang('FIX_USER_DUPLICATION').'</h2>';
		// remove delete users from Agora tables

		$this->db->setQuery('SELECT id, username'.
						' FROM #__users ORDER BY id');
		$users = $this->db->loadAssocList();
		$users_should_stay=array();
		$i=0;
		foreach ($users as $user)
		{
		    $flag=true;
		    foreach ($users_should_stay as $user_should_stay)
		        if($user_should_stay["username"] == $user["username"])
		        $flag=false;
		        
		    if ($flag)
		    {
		        $users_should_stay[$i]=$user;$i++;
		    }
		}
		$where='';
		foreach ($users_should_stay as $user_should_stay)
		{
		    if (!$where)
		    $where .= "( id != ".$user_should_stay["id"];
		    else
		    $where .= " AND id != ".$user_should_stay["id"];
		}
		$where .=' )';
		
		//print_r($where);
		$this->db->setQuery('DELETE FROM #__users WHERE '.$where);
        $this->db->query();

		$where2='';
		foreach ($users_should_stay as $user_should_stay)
		{
		    if (!$where2)
		    $where2 .= "( jos_id != ".$user_should_stay["id"];
		    else
		    $where2 .= " AND jos_id != ".$user_should_stay["id"];
		}
		$where2 .=' )';
        
		$this->db->setQuery('DELETE FROM #__agora_users WHERE '.$where2);
        $this->db->query();
        		
		echo Agora::lang('FIX_USER_DUPLICATION_END')."<br/>\n";
		
	}

	function optimize()
	{
		echo '<h2>'.Agora::lang('Optimize database').'</h2>';
		$service_model = & Model::getInstance('ServiceModel');
		
		$start = microtime(true);
		echo Agora::lang('RUNNING_ON_ALL_TABLES','OPTIMIZE TABLE');
		$service_model->optimize();
		echo ' '.Agora::lang('SERVICE_OK',floatval(microtime(true)-$start))."<br/>\n";

		$start = microtime(true);
		echo Agora::lang('RUNNING_ON_ALL_TABLES','ANALYZE TABLE');
		$service_model->analyze();
		echo ' '.Agora::lang('SERVICE_OK',floatval(microtime(true)-$start))."<br/>\n";
	}
}

?>
